package com.ryder.auth.domain.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ryder.auth.common.enums.IsDeleteFlagEnum;
import com.ryder.auth.domain.convert.AuthPermissionBOConvert;
import com.ryder.auth.domain.entity.AuthPermissionBO;
import com.ryder.auth.domain.redis.RedisUtil;
import com.ryder.auth.domain.service.AuthPermissionDomainService;
import com.ryder.auth.infra.basic.entity.AuthPermission;
import com.ryder.auth.infra.basic.service.AuthPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 描述: (AuthPermission)表服务实现类
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0 // 版本号，指明从哪个版本开始
 * 更新日期: 2025-02-18 02:31:15
 */
@Service
public class AuthPermissionDomainServiceImpl implements AuthPermissionDomainService {
    @Autowired
    private AuthPermissionService authPermissionService;

    @Autowired
    private RedisUtil redisUtil;

    private String authPermissionPrefix = "auth.permission";

    @Override
    public Boolean add(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionBOConvert.INSTANCE.convertBoToEntity(authPermissionBO);
        authPermission.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        Integer count = authPermissionService.insert(authPermission);
        return count > 0;
    }

    @Override
    public Boolean update(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionBOConvert.INSTANCE.convertBoToEntity(authPermissionBO);
        Integer count = authPermissionService.update(authPermission);
        return count > 0;
    }

    @Override
    public Boolean delete(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = new AuthPermission();
        authPermission.setId(authPermissionBO.getId());
        authPermission.setIsDeleted(IsDeleteFlagEnum.DELETED.getCode());
        Integer count = authPermissionService.update(authPermission);
        return count > 0;
    }

    @Override
    public List<String> getPermission(String userName) {
        String permissionKey = redisUtil.buildKey(authPermissionPrefix, userName);
        String permissionValue = redisUtil.get(permissionKey);
        if (StringUtils.isBlank(permissionValue)) {
            return Collections.emptyList();
        }
        List<AuthPermission> permissionList = new Gson().fromJson(permissionValue,
                new TypeToken<List<AuthPermission>>() {
                }.getType());
        List<String> authList = permissionList.stream().map(AuthPermission::getPermissionKey).toList();
        return authList;
    }
}
